package com.stu.boke.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.stu.boke.entity.Tag;
import com.stu.boke.mapper.ArticleTagRefMapper;
import com.stu.boke.mapper.TagMapper;
import com.stu.boke.service.TagService;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class TagServiceImpl implements TagService {
	
	@Autowired(required = false)
	private TagMapper tagMapper;
	
	@Autowired(required = false)
	private ArticleTagRefMapper articleTagRefMapper;

	@Override
	public Integer countTag() {
		return tagMapper.countTag();
	}

	@Override
	public List<Tag> listTag() {
		List<Tag> tagList = null;
        try {
            tagList = tagMapper.listTag();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("获得所有标签失败, cause:{}", e);
        }
        return tagList;
	}

	@Override
	public List<Tag> listTagWithCount() {
		List<Tag> tagList = null;
		try {
			tagList = tagMapper.listTag();
			for (int i = 0; i < tagList.size(); i++) {
				Integer count = articleTagRefMapper.countArticleByTagId(tagList.get(i).getTagId());
				tagList.get(i).setArticleCount(count);
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.error("获得所有标签失败,cause:{}",e);
		}
		return tagList;
	}

	@Override
	public Tag insertSubmitTag(Tag tag) {
		try {
			tagMapper.insert(tag);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("创建分类失败, tag:{}, cause:{}", tag, e);
		}
		return tag;
	}

	@Override
	public Tag getTagById(Integer id) {
		return tagMapper.getTagById(id);
	}

	@Override
	public void updateTag(Tag tag) {
		try {
			tagMapper.update(tag);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("更新分类失败, tag:{}, cause:{}", tag, e);
		}
	}

	@Override
	public void deleteTag(Integer id) {
		try {
			tagMapper.deleteById(id);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("删除分类失败, tag:{}, cause:{}",  e);
		}
	}

}
